package com.woniuxy.redis.lock.service;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * description: SomeService <br>
 * date: 2022/1/7 5:12 下午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */
@Service
public class SomeService {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    RedissonClient redissonClient;

    //下面是版本1
    public String some() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String str = "";
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        //判断缓存中有没有
        if (!redisTemplate.hasKey("str")) {
            //缓存没有就查询数据库
            System.out.println("查询数据库");
            str = "aa";
            opsForValue.set("str", str);
        } else {
            //有就从缓存中取
            System.out.println("查询redis缓存");
            str = (String) opsForValue.get("str");
        }
        return str;
    }
//    public void incr(){
//        redisTemplate.opsForValue().increment("num");
//    }

    //版本2
    public void incr() {
        //设置锁的键名
        RLock mylock = redissonClient.getLock("mylock");
        //加锁
        mylock.lock();
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        //取redis缓存
        Object num = opsForValue.get("num");
        //判断redi缓存是有数据
        if (num == null) {
            //没有的话就存一个
            opsForValue.set("num", "1");
        } else {
            //有就取出来加1
            int count = Integer.parseInt(num.toString());
            count++;
            opsForValue.set("num", count + "");
        }
        //解锁
        mylock.unlock();
    }
}
